//
//  TableViewController.m
//  APIDemo
//
//  Created by 宣佚 on 15/6/1.
//  Copyright (c) 2015年 Andon Health Co,.Ltd. All rights reserved.
//

#import "TableViewController.h"
#import "CloudBL.h"
#import "ViewController.h"
#import <CommonCrypto/CommonDigest.h>
#import <netinet/in.h>
#import <SystemConfiguration/SystemConfiguration.h>

@interface TableViewController ()

@property (nonatomic,strong) NSArray *list;
@property (nonatomic,strong) NSMutableString *LogString;
@property (nonatomic,assign) int logCount;

@end

@implementation TableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cleanLog:) name:@"CleanLogNotification" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(startLog:) name:@"StartLogNotification" object:nil];
    _logCount = 0;
    
     self.clearsSelectionOnViewWillAppear = NO;

    self.list = @[@"申请智能控注册验证码",
                  @"验证手机验证码",
                  @"手机账号注册"];
}

-(void)cleanLog:(NSNotification *)noti
{
    _LogString = [[NSMutableString alloc] init];
}

-(void)startLog:(NSNotification *)noti
{
    NSString *tmpSting = [noti object];
    if ([_LogString isEqualToString:@""] || _LogString == nil) {
        _LogString = [[NSMutableString alloc] init];
        
    }
    [_LogString appendString:[NSString stringWithFormat:@"第%d次请求：\n",_logCount]];
    [_LogString appendString:tmpSting];
    [_LogString appendString:@"\n"];
    [_LogString appendString:@"============================="];
    [_LogString appendString:@"\n"];
}

-(IBAction)logPush:(id)sender
{
    [self performSegueWithIdentifier:@"logPush" sender:_LogString];
}

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:@"logPush"]) {
        ViewController *dview = (ViewController *)segue.destinationViewController;
        dview.text = sender;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
//#warning Incomplete method implementation.
    // Return the number of rows in the section.
    return _list.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
    
    cell.textLabel.text = [NSString stringWithFormat:@"%ld - %@",indexPath.row+1,_list[indexPath.row]];
    
    return cell;
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row % 2 == 1) {
        cell.backgroundColor = [UIColor colorWithRed:0.999 green:0.966 blue:0.927 alpha:1.000];
    } else {
        cell.backgroundColor = [UIColor whiteColor];
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    _logCount++;
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
    switch (indexPath.row) {
        case 0:
            [self GetRegisterVerityCode];
            break;
        case 1:
            [self VerityRegisterCode];
            break;
        case 2:
            [self RegisterUser];
            break;
        default:
            break;
    }
}

/**
 *  申请智能控注册验证码，对应API 1
 */
- (void)GetRegisterVerityCode {
    [CloudBL GetRegisterVerityCode_Phone:@"18502220483"
                                 success:^{
                                     NSLog(@"GetRegisterVerityCode_SUCCESS");
                                     [[NSNotificationCenter defaultCenter] postNotificationName:@"StartLogNotification" object:@"GetRegisterVerityCode_SUCCESS"];
                                 }
                                 failure:^(NSString *errorMessage) {
                                     NSLog(@"GetRegisterVerityCode_ERROR:%@",errorMessage);
                                     [[NSNotificationCenter defaultCenter] postNotificationName:@"StartLogNotification" object:[NSString stringWithFormat:@"GetRegisterVerityCode_ERROR:%@",errorMessage]];
                                 }];
}

/**
 *  验证手机验证码，对应API 2
 */
- (void)VerityRegisterCode {
    [CloudBL VerityRegisterCode_Phone:@"18502220483"
                                 Code:@"613981"
                              success:^(BOOL VerityisSuccess){
                                  NSLog(@"VerityRegisterCode_SUCCESS:%d",VerityisSuccess);
                                  [[NSNotificationCenter defaultCenter] postNotificationName:@"StartLogNotification" object:[NSString stringWithFormat:@"VerityRegisterCode_SUCCESS:%d",VerityisSuccess]];
                              }
                              failure:^(NSString *errorMessage) {
                                  NSLog(@"VerityRegisterCode_ERROR:%@",errorMessage);
                                  [[NSNotificationCenter defaultCenter] postNotificationName:@"StartLogNotification" object:[NSString stringWithFormat:@"VerityRegisterCode_ERROR:%@",errorMessage]];
                              }];
}

/**
 *  手机账号注册，对应API 3
 */
- (void)RegisterUser {
    NSString *pwd = [self SHA1:@"123123" const_Str:@"-6Qg5TyljKlKD~qLu,Y22!UR++4Kep+$" IsLower:YES];
    [CloudBL RegisterUser_Phone:@"18502220483"
                           Code:@"420922"
                       Password:pwd
                        success:^(NSString *iDentity, Token *token) {
                            NSLog(@"RegisterUser_SUCCESS:iDentity - %@ , TokenInfo（accessToken） - %@",iDentity,token.accessToken);
                            [[NSNotificationCenter defaultCenter] postNotificationName:@"StartLogNotification" object:[NSString stringWithFormat:@"RegisterUser_SUCCESS:iDentity - %@ , TokenInfo（accessToken） - %@",iDentity,token.accessToken]];
                        }
                        failure:^(NSString *errorMessage) {
                            NSLog(@"RegisterUser_ERROR:%@",errorMessage);
                            [[NSNotificationCenter defaultCenter] postNotificationName:@"StartLogNotification" object:[NSString stringWithFormat:@"RegisterUser_ERROR:%@",errorMessage]];
                        }];
}

#pragma mark - 密码加密算法

/**
 *  对字符串进行加密
 *
 *  @param topInfo 需要加密的文字
 *  @param const_Str 常量盐值
 *  @param IsLower 是否为小写 设置为YES
 *
 *  @return 加密后的内容
 */
-(NSString *)SHA1:(NSString *)topInfo const_Str:(NSString *)const_Str IsLower:(BOOL)IsLower
{
    NSString *tempMd5 = [NSString stringWithFormat:@"%@%@",const_Str,topInfo];
    NSString *md5 = [self MD5:tempMd5 StringCode:NSUTF8StringEncoding IsLower:YES];
    
    NSString *tempSH = [NSString stringWithFormat:@"%@%@",md5,topInfo];
    
    const char *cstr = [tempSH cStringUsingEncoding:NSUTF8StringEncoding];
    NSData *data = [NSData dataWithBytes:cstr length:tempSH.length];
    uint8_t digest[CC_SHA1_DIGEST_LENGTH];
    
    CC_SHA1(data.bytes, (CC_LONG)data.length, digest);
    
    NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
    
    for(int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++)
    {
        [output appendFormat:@"%02x", digest[i]];
    }
    if (IsLower) {
        return [output lowercaseString];
    } else {
        return [output uppercaseString];
    }
    return output;
}

-(NSString *)MD5:(NSString *)topInfo StringCode:(NSStringEncoding)encode IsLower:(BOOL)IsLower
{
    NSData *data = [topInfo dataUsingEncoding:encode];
    Byte * myByte = (Byte *)[data bytes];
    unsigned char result[16];
    CC_MD5( myByte, (CC_LONG)[data length], result);
    NSMutableString *hash = [NSMutableString string];
    for (int i = 0; i < 16; i++)
    {
        [hash appendFormat:@"%02X", result[i]];
    }
    if (IsLower) {
        return [hash lowercaseString];
    } else {
        return [hash uppercaseString];
    }
}

@end
